# coding=utf-8
"""
监控支付情况，最近十分钟都没有支付的话就报警
crontab 8:00~24:00每分钟执行
使用信鸽新的SDK: pip install xinge_push
"""
import os
import sys
import datetime

base_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.append(base_dir)
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "base.settings")

import xinge_push

from common.pay.model import Pay, PAY_STATUS
from common.utils.tz import local_now

ACCESS_ID = "2100262187"
SECRET_KEY = "cc34df56d3d63b37a28d2de72d99243b"


def monitor(minutes=10):
    time_delta = minutes * 60
    last_pay = Pay.query.filter(Pay.status == PAY_STATUS.DONE) \
        .order_by(Pay.updated_at.desc()).first()
    now = datetime.datetime.utcnow()
    if (now - last_pay.updated_at).seconds > time_delta:
        title = u"CP充值异常"
        body = u"CP超过%s分钟没有成功充值, %s" % (minutes, local_now())
        result = xinge_push.PushAllAndroid(
            ACCESS_ID, SECRET_KEY, title.encode('utf-8'), body.encode('utf-8'))
        print result


if __name__ == "__main__":
    if len(sys.argv) == 1:
        minutes = int(sys.argv[1])
        monitor(minutes)
    else:
        monitor()
